import { defineStore } from "pinia"

export const useSocketStore = defineStore("socket", {
    state: () => ({
        socket: null,
        isConnected: false,
        handlers: [],
    }),
    getters: {
    },
    actions: {
        // 连接WebSocket
        connect() {
            if (this.socket || this.isConnected) return;
            const ws_dashboard = import.meta.env.VITE_APP_WS_DASHBOARD
            this.socket = new WebSocket(ws_dashboard);
            this.socket.onopen = () => {
                this.isConnected = true;
                console.log('WebSocket connected');
            };
            this.socket.onmessage = (event) => {
                const data = JSON.parse(event.data)
                this.handlers.forEach(handler => handler(data));
            };
            this.socket.onerror = (event) => {
                console.error('WebSocket error:', event);
            };
            this.socket.onclose = () => {
                this.isConnected = false;
                console.log('WebSocket closed');
            };
        },
        // 发送消息
        send(message) {
            if (this.socket && this.isConnected) {
                this.socket.send(message);
            }
        },
        // 断开连接
        disconnect() {
            if (this.socket) {
                this.socket.close();
                this.socket = null;
                this.isConnected = false;
            }
        },
        registerHandler(handler) {
            const exists = this.handlers.some(h => h === handler)
            if (!exists) {
                this.handlers.push(handler);
            }
        },
        unregisterHandler(handler) {
            const index = this.handlers.indexOf(handler);
            if (index !== -1) {
                this.handlers.splice(index, 1);
            }
        },
        clickMsgSend() {
            this.send(localStorage.getItem("user_info"));
        }
    }
})